package io.renren.modules.wmstate.service.impl;
// TokenServiceImpl.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.modules.wmstate.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

@Service
public class TokenServiceImpl implements TokenService {

    private static final String TOKEN_URL = "http://10.142.3.129:8080/getOpenApiToken";
    private static final String KEY = "cmhi2023";

    private String token;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String getMachineToken() {
        if (token == null) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("key", KEY);

            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

            ResponseEntity<String> response = restTemplate.postForEntity(TOKEN_URL, request, String.class);

            // 解析响应以获取token
            token = parseToken(response.getBody());
        }

        return token;
    }

    private String parseToken(String responseBody) {
        // 使用Jackson库来解析JSON响应
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode root = objectMapper.readTree(responseBody);
            return root.path("data").path("token").asText();
        } catch (IOException e) {
            throw new RuntimeException("Failed to parse token from response", e);
        }
    }
}

